package leetcode;

public class Code005_ReverseBetween {

    public static class Node {
        int val;
        Node next;

        public Node(int val) {
            this.val = val;
        }

        public Node(int val, Node next) {
            this.val = val;
            this.next = next;
        }
    }

    public static Node reverseBetween(Node head, int left, int right) {

        Node dummy = new Node(-1);
        dummy.next = head;

        Node pre = dummy;
        for(int i = 1; i < left; i++){
            pre = pre.next;
        }
        Node cur = pre.next, next;
        for(int i = 0; i < right - left; i++){
            next = cur.next;
            cur.next = next.next;
            next.next = pre.next;
            pre.next = next;
        }
        return dummy.next;
    }

    public static void printList(Node head) {
        while (head != null) {
            System.out.print(head.val + (head.next != null ? "->" : "\n"));
            head = head.next;
        }
    }

    public static void main(String[] args) {
        Node n1 = new Node(1);
        Node n2 = new Node(2);
        Node n3 = new Node(3);
        Node n4 = new Node(4);
        Node n5 = new Node(5);
        //Node n6 = new Node(6);
//        n1.next = n2;
//        n2.next = n3;
//        n3.next = n4;
//        n4.next = n5;
        //n5.next = n6;
        n3.next = n5;
        Node head = reverseBetween(n3, 1, 2);
        printList(head);


    }
}
